﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using DataEntity;
using Newtonsoft.Json;

namespace SensorMonitor
{
    class ProcessRx : TwinSim
    {
        
        private static HFILE hfile = new HFILE();

        private static void InstLoop(string sMsg)
        {
            //string s;

            int f = m_dll.doIsCascade(sMsg);
            switch (f)
            {
                case 1: //TRUE
                    String jSeg = m_dll.Parse("G_PROFILE", sMsg);

                    SEG_PARSED segParsed = new SEG_PARSED();
                    segParsed = (SEG_PARSED)JsonConvert.DeserializeObject(jSeg, segParsed.GetType());

                    HFILE retFile = FileMerge(segParsed);         //合并
                    if (retFile == null)
                    {
                        return;
                    }       //合并未完成，继续等待后续msg

                    //file ready !
                    if (m_dll.doCheckPack(retFile.hex) == true){
                        //string sFile = m_dll.doDePack(retFile.hex);
                        Console.Write("\r\n" + "sCfg restore ok !");
                    }else{
                        Console.Write("\r\n" + "sCfg restore failed !");
                    }
                    break;

                case 0: //FALSE
                    //sMsg = "4A310060011015FE4D535F534C4545503D30783836303B20756C4D73436C69636B3D30783835342032323A31323A3339D5F4";
                    String jInfo = m_dll.Parse("G_INFO", sMsg);
                    if (jInfo == "") {
                        Console.Write("\r\n" + "Msg error when GetInfoOf():" + sMsg);
                        string s0 = m_dll.Parse("G_INFO", sMsg);
                        break;
                    }

                    INFO_MSG infoParsed = new INFO_MSG();
                    infoParsed = (INFO_MSG)JsonConvert.DeserializeObject(jInfo, infoParsed.GetType());

                    if (infoParsed._Op == "msg_belt")
                    {
                        //int outContent = 1; //0: OUT_belt; 1:OUT_belt&rec
                        string sOut0 = m_dll.Parse("G_INSTANT", sMsg, TwinSim.Rfg);   //sCfg, sMdl);
                        //string sOut1 = m_dll.Parse("G_DETAIL", sMsg, sCfg, sMdl);
                        Console.Write("Msg parsed : " + sOut0);
                    }
                    //sLMsg = sMsg;
                    break;

                case -1: //ERROR
                    Console.Write("Illegal hex-Msg");
                    break;
            }
        }


        //Fill blanks, one by one.
        private static HFILE FileMerge(SEG_PARSED segParsed)
        {
            
            string k = segParsed._FileName + "_" + segParsed._FileId;
            string sExist;

            if (fileMap.ContainsKey(k) == false)
            {  //fileMap中：不存在的新文件
                sExist = InitFileMap(segParsed);    //new
            }
            else
            {   //fileMap中存在的文件
                sExist = fileMap[k];
            }

            //replace "[xxx]" with s[]
            string sMark = "[" + segParsed._SegIndex + "]";
            //
            int pos = sExist.IndexOf(sMark);
            if (pos < 0)
            {
                fileMap.Remove(k);       //恢复到起始状态
                //TextOut.println(KGet.HHmmSS() + " Merge-mark" + sMark + " not found.");
                return null;
            }

            string s = segParsed._SegHex.Substring(1*2);  //skip SegLen
            string sResult = sExist.Replace(sMark, s);
            //"[0][1][2] 487801...E74D [123][124]"

            // all : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", no "["
            if (sResult.IndexOf("[") < 0){
                fileMap.Remove(k);       //恢复到起始状态
                //
                hfile.name = segParsed._FileName + "_" + segParsed._FileId;
                hfile.hex = sResult; 
                return hfile;
            }        //Completed !
            else{
                fileMap[k] = sResult;
            }

            return null;
        }

        // Init as : "[0][1][2] ... [123][124]"
        private static String InitFileMap(SEG_PARSED segParsed)
        {
            int size = Convert.ToInt16(segParsed._Segs);
            String s = "";
            for (int i = 0; i < size; i++)
            {
                s += "[" + Convert.ToString(i) + "]";
            }

            string k = segParsed._FileName + "_" + segParsed._FileId;
            fileMap[k] = s;
            return s;
        }



        //合并/处理Msg
        public static void AckProcess()
        {

            while (fStop == false)
            {
                while (term.queueRxMsg.Count > 0)
                {
                    string sMsg = term.queueRxMsg.Dequeue();
                    //string sIn = strip215FP(sMsg);

                    InstLoop(sMsg);

                    //string s = m_dll.doGetInfoOf(sIn);
                    //txtExplicit.AppendText("\r\n" + s);
                }
                Thread.Sleep(500);
            }
        }
    }
}
